//
//  ZHPopoverCategoryView.swift
//  ZZLeSay
//
//  Created by 赵正华 on 16/7/28.
//  Copyright © 2016年 赵正华. All rights reserved.
//

import UIKit


protocol popverCategoryViewDelegate {
    func selectedCategoryEndWithIndex(index : NSInteger)
}
class ZHPopoverCategoryView: UIView {

     var delegate: popverCategoryViewDelegate?
    @IBOutlet weak var exchangeBtn: UIButton!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var keepView: UIView!

    var catergoryTitles : [String]?{
        didSet{
         createScrollCategory(catergoryTitles!)
         popverView = createPopoverView(catergoryTitles!)
        
        }
    }
    //遮挡view
    lazy var maskCoverView : ZHCoverView = {
         let coverView = ZHCoverView()
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(self.hiddenCover))
        coverView.addGestureRecognizer(tap)
         return coverView
    }()
    //scrollview的指示器
     var scrIndicatorView : UIView = {
           let view = UIView()
           view.backgroundColor = UIColor.redColor()
        return view
    }()
    //popverView的指示器
    var popIndicatorView : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.redColor()
        return view
    }()
    
    var tempBtn : UIButton?   //存储按钮状态
    
    /// 弹出分类视图的按钮列数
    var popverBtnColumn = 4
    /// 缓存滚动分类按钮
    var cacheScrollCatergoryBtn = [UIButton]()
    /// 缓存格子分类按钮
    var cacheSquareCatergoryBtn = [UIButton]()
    /// 当前所选的滚动分类按钮
    var seletedScrollBtn : UIButton?
    /// 当前所选的格子分类按钮
    var seletedSquareBtn : UIButton?
    /// 弹出的格子分类视图
    var popverView : UIView?
    /// 是否显示分类视图
    var isShowPopverView = false
    
    class func createPopverCategoryView() -> ZHPopoverCategoryView {
      return  (NSBundle.mainBundle().loadNibNamed("ZHPopoverCategoryView", owner: nil, options: nil).first as? ZHPopoverCategoryView)!
    }
    override func awakeFromNib() {
        self.exchangeBtn.selected = false
        self.scrollView.showsHorizontalScrollIndicator = false
        self.keepView.hidden = true
    }
    private func createScrollCategory(titles : [String]?){
        
        var buttonW : CGFloat = 0
        let buttonH : CGFloat = 44
        let buttonY : CGFloat = 0
        var buttonX : CGFloat = 0
        var contentSizeW : CGFloat = 0
        
        for i in 0..<(titles?.count)! {
            let title = titles![i]
            let ScrollBtn = UIButton(type: .Custom)
            buttonW = title.boundingRectWithSize(CGSizeZero, options: NSStringDrawingOptions(rawValue: 0), attributes: [NSFontAttributeName : ScrollBtn.titleLabel!.font], context: nil).width + 10
            buttonX = cacheScrollCatergoryBtn.last == nil ? 0.0 : CGRectGetMaxX(cacheScrollCatergoryBtn.last!.frame)
            ScrollBtn.tag = i
            ScrollBtn.frame = CGRectMake(buttonX,buttonY, buttonW, buttonH)
            ScrollBtn.setTitle(titles![i], forState: .Normal)
            ScrollBtn.setTitleColor(UIColor.grayColor(), forState: .Normal)
            ScrollBtn.titleLabel?.font = UIFont.systemFontOfSize(13)
            
            ScrollBtn.addTarget(self, action: #selector(self.clickScrollBtn(_:)), forControlEvents: .TouchUpInside)
            cacheScrollCatergoryBtn.append(ScrollBtn)
            contentSizeW = contentSizeW + buttonW
            self.scrollView.addSubview(ScrollBtn)
            if i == 0 {
              self.scrollView.addSubview(scrIndicatorView)
              scrIndicatorView.frame = CGRectMake(0, ScrollBtn.frame.size.height - 2,buttonW - 10, 2)
              scrIndicatorView.center.x = ScrollBtn.center.x
            }
        }
        self.scrollView.contentSize = CGSizeMake(contentSizeW, 0)
    }
    private func createPopoverView(titles : [String]?) ->ZHBeziderView?{
          let popView = ZHBeziderView()
          let buttonW = kScreenWidth / CGFloat(popverBtnColumn)
          let buttonH : CGFloat = 44
        for i in 0..<(titles?.count)! {
            let buttonX = (i) % popverBtnColumn
            let buttonY = (i) / popverBtnColumn
            let squareBtn = UIButton(type: .Custom)
            squareBtn.tag = i
            squareBtn.frame = CGRectMake(CGFloat(buttonX) * buttonW,CGFloat(buttonY) * buttonH, buttonW, buttonH)
            squareBtn.setTitle(titles![i], forState: .Normal)
            squareBtn.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
            squareBtn.setTitleColor(UIColor.redColor(), forState: .Selected)
            squareBtn.titleLabel?.font = UIFont.systemFontOfSize(13)
            squareBtn.addTarget(self, action: #selector(self.clickPopViewBtn(_:)), forControlEvents: .TouchUpInside)
            cacheSquareCatergoryBtn.append(squareBtn)
            popView.addSubview(squareBtn)
            if i == 0 {
                popView.addSubview(popIndicatorView)
                popIndicatorView.frame = CGRectMake(0,buttonH - 2,buttonW, 2)
                self.clickPopViewBtn(squareBtn)
            }
        }
        popView.frame = CGRectMake(0, -buttonH * CGFloat((((titles?.count)! - 1) / 4 + 1)), kScreenWidth,buttonH * CGFloat((((titles?.count)! - 1) / 4 + 1)))
        popView.backgroundColor = UIColor.whiteColor()
        superview!.insertSubview(popView, belowSubview: self)
        return popView
    }
   
}
extension ZHPopoverCategoryView{
    //点击scrollView上按钮的点击事件
    @objc func clickScrollBtn(button:UIButton){
        UIView.animateWithDuration(0.25, animations: { 
            self.scrIndicatorView.frame = CGRectMake(0, button.frame.size.height - 2,button.frame.size.width - 10, 2)
            self.scrIndicatorView.center.x = button.center.x
            }) { (_) in
                UIView.animateWithDuration(0.25, animations: {
                    self.changeScrollViewOffset(button)
                })
                let tag = button.tag
                let btn = self.cacheSquareCatergoryBtn[tag] 
                self.clickPopViewBtn(btn)
        }
       delegate?.selectedCategoryEndWithIndex(button.tag)
    }
    //点击popView上按钮的点击事件
    @objc func clickPopViewBtn(button:UIButton){
        
        button.selected = true
        self.tempBtn?.selected = false
        self.tempBtn = button
        self.exchangeBtn.selected = false
        
        UIView.animateWithDuration(0, animations: { 
            self.popIndicatorView.frame = CGRectMake(button.frame.origin.x, button.frame.origin.y + button.frame.size.height - 2,button.frame.size.width, 3)
            }) { (_) in
                let tag = button.tag
                let btn = self.cacheScrollCatergoryBtn[tag]
            self.scrIndicatorView.frame = CGRectMake(0, btn.frame.size.height - 2,btn.frame.size.width - 10, 2)
                self.scrIndicatorView.center.x = btn.center.x
                self.changeScrollViewOffset(btn)
                self.showPopverView()
        }
        delegate?.selectedCategoryEndWithIndex(button.tag)
    }
    //遮挡层手势方法
    @objc func hiddenCover(){
        self.showPopverView()
        exchangeBtn.selected = false
    }
    //展开popverView的按钮
    @IBAction func clickExchangeBtn(sender: UIButton) {
        if !sender.selected {
            self.hidePopverView()
            sender.selected = true
        }else{
            self.showPopverView()
            sender.selected = false
        }
    }
     //显示popverView
   private func showPopverView(){
        UIView.animateWithDuration(0.5) {
            self.popverView!.frame.origin.y = -self.popverView!.frame.size.height
            self.keepView.hidden = true
            self.maskCoverView.removeFromSuperview()
        }
    }
     //隐藏popverView
    private func hidePopverView(){
        UIView.animateWithDuration(0.5) {
            self.popverView!.frame.origin.y = self.frame.size.height
             self.keepView.hidden = false
        }
        superview!.insertSubview(maskCoverView, belowSubview: popverView!)
    }
}
extension ZHPopoverCategoryView{
    
    //点击scrollView上面的按钮滚到对应的位置上
    private func changeScrollViewOffset(button : UIButton){
       let btnX = button.center.x
        if btnX > kScreenWidth * 0.5 {
             if scrollView.contentSize.width > bounds.width && btnX > bounds.width * 0.5 && btnX < (scrollView.contentSize.width - bounds.width * 0.5)  {
                scrollView.setContentOffset(CGPointMake(button.frame.origin.x + button.bounds.width * 0.5 - bounds.width * 0.5, 0), animated: true)
            }else{
            scrollView.setContentOffset(CGPointMake(max(scrollView.contentSize.width - scrollView.bounds.size.width, 0), 0), animated: true)
            }
        }else{
            scrollView.setContentOffset(CGPointZero, animated: true)
        }
    }
}
